package controller;

import com.github.pagehelper.PageInfo;
import entity.Admin;
import entity.LayRequest;
import entity.MyResult;
import entity.Role;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import service.AdminService;
import service.RoleService;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminService adminService;
    @RequestMapping("/toadd")
    public String toadd(ModelMap modelMap){
        //查询所有的角色信息
        List<Role> roles=roleService.selectAll();
        //将角色信息返回到前台页面
        modelMap.addAttribute("roles",roles);
        return "add.jsp";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Admin admin,HttpSession session){
        adminService.insert(admin);
        return "redirect:list";
    }
    //RequestParam  用来获取前台传递的值，如果有name属性，name只获取对应name的数据
    //如果没有指定，则获取所有的数据
    @RequestMapping("/list")
    public String list(@RequestParam Map<String, Object> map, ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> adminPageInfo=adminService.selectByPage(map);
        //将分页查询结果传递给页面
        modelMap.addAttribute("page",adminPageInfo);
        modelMap.addAttribute("params",map);
        return "list.jsp";
    }
    @ResponseBody
    @RequestMapping("/layList")
    public MyResult<List<Admin>> layList(LayRequest layRequest, ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> adminPageInfo=adminService.selectByPage(layRequest);
        //将分页查询结果传递给页面
        return new MyResult<>(0,adminPageInfo.getTotal(),adminPageInfo.getList());
    }

    @ResponseBody//表示返回json数据
    @RequestMapping(value = "/delete",method = RequestMethod.GET)//等同于@GetMapping("/delete")
    public MyResult delete(Integer id){
        boolean flag = adminService.delete(id);
        return flag?new MyResult(200,"删除成功！")
                :new MyResult(200,"删除失败");
    }
    //在方法参数中定义Httpsession,HttpServiceRequest等对象，springmvc自动把对象传入
    @PostMapping("/login")
    public String login(String account, String password, HttpSession session){
        //根据用户名查用户是否存在
        Admin admin = adminService.selectByAccount(account);
        if (admin!=null &&admin.getPassword().equals(password)){
            //将用户信息放入session
            session.setAttribute("admin",admin);
            //查询用户拥有的菜单
            Role role = roleService.selectById(admin.getRoleid());
            //将角色和权限信息存放到session域
            session.setAttribute("role",role);
            return "redirect:/index.jsp";
        }
        return "/login.jsp";//以/开头就是绝对路径
    }
    //@SessionAttribute("admin")
    //MultipartFile 对象来接受上传文件，参数名与input中name名一致
    @RequestMapping("/headpic")
    public String headpic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException {
        String filename = headpic.getOriginalFilename();
        System.out.println("上传文件名："+filename);
        File file=new File("E:/headpic/"+filename);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();//如果父目录不存在，创建新目录
        }
        //保存文件，将上传的文件内容写入file
        headpic.transferTo(file);
        admin=new Admin(id);
        //将头像路径保存到对象中
        admin.setHeadpic("/head/"+filename);
        adminService.updateHeadPic(admin);
        return "redirect:list";
    }
    @GetMapping("/headpicDowmload")
    public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException {
        File file=new File("E:/headpic/"+filename);
        //2.读取文件内容
        byte[] bytes= FileUtils.readFileToByteArray(file);
        //3.设置http响应头
        HttpHeaders headers=new HttpHeaders();
        //设置ContentType为stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置已附件形式打开
        headers.setContentDispositionFormData("attachment",filename);
        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
    }
}
